//
//  SZLSellerAddGoodsViewController.m
//  Shengzhuli
//
//  Created by subook on 16/8/11.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLSellerAddGoodsViewController.h"
#import "MainPageLocationTableViewCell.h"

#import "SZLAccountHelper.h"
#import "SuModelTool.h"
#import "AddGoodsModel.h"
#import "BusinessNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "AddGoodsPriceCell.h"
#import "StoreIntroduceTableViewCell.h"
#import "AddImageCell.h"
#import "TakePhotoTool.h"
#import "VefityTool.h"
#import "ConGoodsTypeViewController.h"
#import "CWNumberKeyboard.h"
#import "IQKeyboardManager.h"
#import "IQUIView+Hierarchy.h"

@interface SZLSellerAddGoodsViewController () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,weak) UITableView *tableView;
@property (nonatomic,strong) AddGoodsModel *model;//修改商品请求回来的商品详情
@property (nonatomic,weak) UIButton *sureButton;

@property (nonatomic,strong) NSArray *oneTitles;
@property (nonatomic,strong) NSArray *twoTitles;
@property (nonatomic,strong) NSArray *oneTips;
@property (nonatomic,strong) NSArray *twoTips;
@property (nonatomic,strong) CWNumberKeyboard *priceKeyBoard;
@property (nonatomic,strong) UIView *footerView;
/* 
 记录上传图片的btn和type
 **/
@property (nonatomic,strong) AddImageButton *btn;
@property (nonatomic,assign) AddImageCellType cellType;

@property (nonatomic,strong) NSArray *secondTypes;//二级分类数组 自己带过去

@end

@implementation SZLSellerAddGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    [self createSureButton];
    if (self.type == SellerGoodsTypeAdd) {
        self.navigationItem.title = @"新增商品";
        [self.sureButton setTitle:@"保存" forState:(UIControlStateNormal)];
        self.model = [[AddGoodsModel alloc]init];
        self.model.price = -1;
        self.model.freightInMaxCount = -1;
        self.model.freightInEveryAdd = -1;
        [self createTableView];
    }else{
        self.navigationItem.title = @"修改商品";
        [self.sureButton setTitle:@"修改并上传" forState:(UIControlStateNormal)];
        [self requestModifyGoods];
    }
    [self addObserve];
}
#pragma mark ------------所修改的商品的请求------------------------
- (void)requestModifyGoods
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"productNo"] = self.productNumber;
    [self showWaiter];
    [BusinessNetwork getShopGoodsDetailWithParame:params response:^(BOOL success, NSString *msg, AddGoodsModel *model) {
        [self hideWaiter];
        if (success) {
            self.model = model;
            [self createTableView];
            if (self.successBlock) {
                self.successBlock();
            }
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)createSureButton
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 60)];
    footerView.backgroundColor = [UIColor whiteColor];
    UIButton *sureButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    sureButton.frame = CGRectMake(10, 10, ScreenW-20, 40);
    [sureButton setBackgroundImage:GetImage(@"btn_bg_login_normal") forState:UIControlStateNormal];
    [sureButton setBackgroundImage:GetImage(@"btn_bg_login_normal") forState:UIControlStateHighlighted];
    sureButton.layer.cornerRadius = 5;
    [sureButton addTarget:self action:@selector(saveButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.sureButton = sureButton;
    [footerView addSubview:sureButton];
    self.footerView = footerView;
}
- (void)createTableView
{
    self.oneTitles = @[@"商品分类",@"商品标题",@"商品副标题",@"价格",];
    self.oneTips = @[@"请选择商品分类",@"请输入商品标题",@"请输入商品副标题",@"请输入商品价格"];
    UITableView *tableView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 0, ScreenW, ScreenH-64)) style:(UITableViewStyleGrouped)];
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddGoodsPriceCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([AddGoodsPriceCell class])];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddImageCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([AddImageCell class])];
    tableView.tableFooterView = self.footerView;
    self.tableView = tableView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.oneTitles.count+1;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row != 4) {
            return 50;
        }
        if (self.model.productBannerList.count<4) {
            return ImageWidth+48;
        }
        NSInteger row = (self.model.productBannerList.count+1+4-1)/4.0-1;
        return ImageWidth+48+(ImageWidth+10)*row;
    }else {
        if (self.model.productDetailList.count<4) {
            return ImageWidth+48;
        }
        NSInteger row = (self.model.productDetailList.count+1+4-1)/4.0-1;
        return ImageWidth+48+(ImageWidth+10)*row;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row != 4) {
            AddGoodsPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AddGoodsPriceCell class])];
            cell.nameStr = self.oneTitles[indexPath.row];
            cell.placeHolder = self.oneTips[indexPath.row];
            cell.tags = indexPath.row;
            cell.model = self.model;
            cell.fieldDelegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        AddImageCell *cell = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([AddImageCell class]) owner:self options:nil]lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.type = AddImageCellTypeBanners;
        cell.model = self.model;
        __WEAK
        cell.deleteBlock = ^(AddImageCellType type){
            [weakSelf.tableView reloadData];
        };
        cell.addImageBlock = ^(AddImageCellType type,AddImageButton *btn){
            [weakSelf.view endEditing:YES];
            self.cellType = type;
            weakSelf.btn = btn;
            [self takePhoto];
        };
        return cell;
    }
    //取消重用 减小复杂度
    AddImageCell *cell = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([AddImageCell class]) owner:self options:nil]lastObject];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.type = AddImageCellTypeGoodsDetail;
    cell.model = self.model;
    __WEAK
    cell.deleteBlock = ^(AddImageCellType type){
        [weakSelf.tableView reloadData];
    };
    cell.addImageBlock = ^(AddImageCellType type,AddImageButton *btn){
        [weakSelf.view endEditing:YES];
        self.cellType = type;
        weakSelf.btn = btn;
        
        [self takePhoto];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    if (indexPath.section == 0&&indexPath.row == 0) {
        ConGoodsTypeViewController *typeVc = [[ConGoodsTypeViewController alloc]init];
        typeVc.type = SelectTypeUpGoods;
        __WEAK
        typeVc.selectBlock = ^(HomeGoodsTypeModel *model) {
            weakSelf.model.productType = model.productTypeName;
            weakSelf.model.isInIndexActivity = model.ID;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
        };
        [self.navigationController pushViewController:typeVc animated:YES];
    }
}
- (void)saveButtonClick:(UIButton *)button
{
    [self.view endEditing:YES];
    BOOL isValid = [self checkGoodsDetails];
    if (!isValid) return;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"isInIndexActivity"] = @(self.model.isInIndexActivity);
    params[@"name"]  = self.model.name;
    params[@"subtitle"]  = self.model.subtitle;
    params[@"price"]  = @(self.model.price);
//    params[@"freightInMaxCount"] = @(self.model.freightInMaxCount);
//    params[@"freightInEveryAdd"] = @(self.model.freightInEveryAdd);
    params[@"freightInMaxCount"] = @"0";
    params[@"freightInEveryAdd"] = @"0";

    params[@"productBanner"]  = [self.model.productBannerList componentsJoinedByString:@"#"];
    params[@"productDetail"]  = [self.model.productDetailList componentsJoinedByString:@"#"];
//    params[@"bannerUrl"]  = [self.model.bannerList componentsJoinedByString:@"#"];
    params[@"bannerUrl"] = @"0";
     if (self.type == SellerGoodsTypeShow) {
        params[@"productNo"] = self.model.productNo;
        [self showWaiter];
        [BusinessNetwork modifyGoodsDetailWithParame:params response:^(BOOL success, NSString *msg) {
            [self hideWaiter];
            if (success) {
                [MBProgressHUD showSuccess:@"修改商品信息成功" toView:self.view];
                if (self.successBlock) {
                    self.successBlock();
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else{
                [MBProgressHUD showError:msg toView:self.view];
            }
        }];
    }else{
        [self showWaiter];
        [BusinessNetwork addGoodsWithParame:params response:^(BOOL success, NSString *msg) {
            [self hideWaiter];
            if (success) {
                [MBProgressHUD showSuccess:@"添加商品成功" toView:self.view];
                if (self.successBlock) {
                    self.successBlock();
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else{
                [MBProgressHUD showError:msg toView:self.view];
            }
        }];
    }
}
- (BOOL)checkGoodsDetails
{
    if (!self.model.isInIndexActivity) {
        [MBProgressHUD showError:@"请选择商品分类" toView:self.view];
        return NO;
    }
    if (self.model.name.length<1) {
        [MBProgressHUD showError:@"商品标题不能为空" toView:self.view];
        return NO;
    }
    if (self.model.subtitle.length<1) {
        [MBProgressHUD showError:@"商品副标题不能为空" toView:self.view];
        return NO;
    }
    if (![VefityTool isValidNumber:[NSString stringWithFormat:@"%f",self.model.price]]) {
        [MBProgressHUD showError:@"商品价格不是有效数字" toView:self.view];
        return NO;
    }
    if (self.model.productBannerList.count<1) {
        [MBProgressHUD showError:@"商品详情页轮播图不能为空" toView:self.view];
        return NO;
    }
    
//    if (![VefityTool isValidNumber:[NSString stringWithFormat:@"%f",self.model.freightInMaxCount]]) {
//        [MBProgressHUD showError:@"运费价格不是有效数字" toView:self.view];
//        return NO;
//    }
//    if (![VefityTool isValidNumber:[NSString stringWithFormat:@"%f",self.model.freightInEveryAdd]]) {
//        [MBProgressHUD showError:@"多件设置运费不是有效数字" toView:self.view];
//        return NO;
//    }
    
    if (self.model.productDetailList.count<1) {
        [MBProgressHUD showError:@"商品详情不能为空" toView:self.view];
        return NO;
    }
//    if (self.model.bannerList.count<3) {
//        [MBProgressHUD showError:@"活动图片需要上传3个" toView:self.view];
//        return NO;
//    }
    return YES;
}
#pragma mark --------------选择照片及处理---------------------
- (void)takePhoto
{
    __WEAK
    [[TakePhotoTool shareTool] beginSelectWithScale:0 image:^(UIImage *image, NSString *path) {
        [weakSelf.btn setBackgroundImage:image forState:UIControlStateNormal];
        switch (self.cellType) {
            case AddImageCellTypeBanners:
            {
                [weakSelf.model.productBannerList addObject:path];
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
            }
                break;
            case AddImageCellTypeGoodsDetail:
            {
                [self.model.productDetailList addObject:path];
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationLeft];
            }
                break;
            case AddImageCellTypeActivity:
            {
                [self.model.bannerList addObject:path];
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:3]] withRowAnimation:UITableViewRowAnimationLeft];
            }
                break;
                
            default:
                break;
        }
    }];
}
- (void)addObserve
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}
//监听文字输入
- (void)textFieldChanged:(NSNotification *)noti
{
    UITextField *field = noti.object;
    switch (field.tag) {
        case 1:
        {
            self.model.name = field.text;
        }
            break;
        case 2:
        {
            self.model.subtitle = field.text;
        }
            break;
        default:
            break;
    }
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (!textField.isAskingCanBecomeFirstResponder) {
        if (textField.tag>=3) {
            [self.view endEditing:YES];
            if (!self.priceKeyBoard) {
                self.priceKeyBoard = [[CWNumberKeyboard alloc] init];
                [self.view addSubview:self.priceKeyBoard];
            }
            [self.priceKeyBoard setHidden:NO];
            __WEAK
            [self.priceKeyBoard showNumKeyboardViewAnimateWithPrice:@"" andBlock:^(NSString *priceString) {
                textField.text = priceString;
                if (textField.tag == 3) {
                    weakSelf.model.price = [priceString floatValue];
                }else if (textField.tag == 4){
                    weakSelf.model.freightInMaxCount = [priceString floatValue];
                }else if (textField.tag == 5){
                    weakSelf.model.freightInEveryAdd = [priceString floatValue];
                }
            }];
            return NO;
        }
    }
    return YES;
}

- (NSNumber *)transStringToNum:(NSString *)str
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    return [numberFormatter numberFromString:str];
}

@end
